const util =require("../../utils/util")
// pages/chat/chat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  onLoad: function (options) {
       console.log(options.id)
    this.setData({
      recordId:options.id
    })
    this.getmyid()
    this.getChatRecord()
  },
  //我的信息
  getmyid(){
    let that = this;
    var _id = wx.getStorageSync('istokenid')
    wx.cloud.database().collection('chat_user').doc(
      _id
    ).get().then(res=>{
      console.log(res);
      that.setData({
        userInfo:res.data
      })
    })
  },
//获取聊天记录
  getChatRecord(){
    var that = this;
    wx.cloud.database().collection('chat_record').doc(that.data.recordId).get().then(res=>{
      console.log(res);
      that.setData({
        chatList:res.data.RECORD
      })
    })
  },
  //输入框
  getInputValue(event){
    console.log(event.detail.value)
    this.data.inputValue = event.detail.value
  },
  // 发布
  publishChat(){
    var that = this;
    wx.cloud.database().collection('chat_record').doc(that.data.recordId).get({
      success(res){
        console.log(res)
        var RECORD = res.data.RECORD
        var msg = {}
        msg.userId = that.data.userInfo._id
        msg.nickName = that.data.userInfo.nickName
        msg.faceImg = that.data.userInfo.faceImg
        msg.openid = that.data.userInfo._openid
        msg.text = that.data.inputValue
        msg.time = util.formatTime(new Date())
        RECORD.push(msg)
        wx.cloud.database().collection('chat_record').doc(that.data.recordId).update({
          data: {
            RECORD: RECORD
          },
          success(res){
            console.log(res)
            wx.showToast({
              title: '发布成功！',
            })
            
            //刷新下
            that.getChatRecord()

            that.setData({
              inputValue :'',
              plcaceHolder:'评论'
            })
          }
        })

      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})